//
//  HDCFBuyFundVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/2.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFBuyMakeUp.h"
#import "SVProgressHUD.h"
#import "InputPassWordView.h"
#import "makeUpTableViewCell.h"
#import "HDCFRiskTestVc.h"
#import "HDCFMyBankCardVc.h"

#define KBankCardInfo @"/public/transaction/get-investor-payment-method"

#define KGetFee @"/public/product/portfolio/purchase-portfolio-transaction-fee"


@interface HDCFBuyMakeUp ()<InputPassWordViewDelegate, UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *bankIcon;
@property (weak, nonatomic) IBOutlet UILabel *bankInfo;
@property (weak, nonatomic) IBOutlet UILabel *fundName;
@property (weak, nonatomic) IBOutlet UILabel *fundCode;
@property (weak, nonatomic) IBOutlet UITextField *moneyTf;
@property (weak, nonatomic) IBOutlet UILabel *riskLevel;

//参考费率
@property (weak, nonatomic) IBOutlet UILabel *consultRate;
//参考费用
@property (weak, nonatomic) IBOutlet UILabel *consultCost;
@property (weak, nonatomic) IBOutlet UILabel *downBuyMoney;
@property (nonatomic, strong) NSArray *bankArray;
@property (nonatomic, strong) NSDictionary *bankDetail;
@property (weak, nonatomic) IBOutlet UILabel *limitMoney;
@property (nonatomic, weak) UIView *hitView;
@property (nonatomic, assign) double maxMoney;
@property (nonatomic, assign) double minMoney;
@property (nonatomic, copy) NSString *tradePassword;
@property(nonatomic,strong)UIView *clearHudView;

@property (nonatomic, strong) NSArray *fundArray;

@property (nonatomic, assign) CGFloat buyMoney;

@property (nonatomic, assign) BOOL isBankCard;
@property (nonatomic, copy) NSString *investorPayId;

@end

@implementation HDCFBuyMakeUp

- (void)viewDidLoad {
    [super viewDidLoad];
    self.buyMoney = 0.0;
    self.consultRate.hidden = YES;
    self.moneyTf.delegate = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"makeUpTableViewCell" bundle:nil] forCellReuseIdentifier:@"makeUpTableViewCell"];
    
    //注册键盘消失的通
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    [self.navigationItem setTitle:@"组合基金购买"];
//    self.fundCode = _dataDict[@"fundCode"];
    self.fundName.text = _dataDict[@"portfolioName"];
    NSNumber *riskRate = _dataDict[@"portfolioRisk"];
    if (riskRate.integerValue == 1) {
        _riskLevel.text = @"保守型";
    }else if (riskRate.integerValue == 2){
        _riskLevel.text = @"中度保守型";
    }else if (riskRate.integerValue == 3){
        _riskLevel.text = @"平衡型";
    }else if (riskRate.integerValue == 4){
        _riskLevel.text = @"中度进取型";
    }else{
        _riskLevel.text = @"进取型";
    }
    
    
//    if ([fundStatus isEqualToString:@"0"]) {
//        NSNumber *minInitialIpoAmount = _dataDict[@"minInitialIpoAmount"];
//        self.minMoney = minInitialIpoAmount.doubleValue;
//        NSNumber *maxIpoAmount = _dataDict[@"maxIpoAmount"];
//        self.maxMoney = maxIpoAmount.doubleValue;
//        self.limitMoney.text = [NSString stringWithFormat:@"%.2f---%.2f", minInitialIpoAmount.doubleValue, maxIpoAmount.doubleValue];
//    }else if ([fundStatus isEqualToString:@"1"]){
    
        NSNumber *minBuyAmount = _dataDict[@"minBuyAmount"];
        self.limitMoney.text = [NSString stringWithFormat:@"最低购买金额：%.2f", minBuyAmount.doubleValue];
//        self.minMoney = minInitialBuyAmount.doubleValue;
//        self.maxMoney = maxBuyAmount.doubleValue;
//    }
    
    [self initData];
    [self getBankCardInfo];
    [self configerTableFooterView];
}
-(void)configerTableFooterView
{
    UIButton *btnTwoYF = [[UIButton alloc] init];
    btnTwoYF.frame = CGRectMake(0, 0, screenWidth, 50);
    [btnTwoYF setBackgroundColor:ZKcolor(245, 245, 245)];
    NSString *strleft = @"基金销售服务由奕丰金融提供\n-基金有风险 投资需谨慎-";
    NSMutableAttributedString *attrStrT = [[NSMutableAttributedString alloc] initWithString:strleft];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:[UIColor lightGrayColor]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:12]
                     range:NSMakeRange(0, strleft.length)];
    [attrStrT addAttribute:NSFontAttributeName
                     value:[UIFont boldSystemFontOfSize:14]
                     range:NSMakeRange(7, 4)];
    [attrStrT addAttribute:NSForegroundColorAttributeName
                     value:ZKcolor(33, 33, 33)
                     range:NSMakeRange(7, 4)];
    [btnTwoYF setAttributedTitle:attrStrT forState:UIControlStateNormal];
    [btnTwoYF setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btnTwoYF.titleLabel setTextAlignment:NSTextAlignmentCenter];
    btnTwoYF.titleLabel.lineBreakMode = 0;
    [btnTwoYF addTarget:self action:@selector(presentPage) forControlEvents:UIControlEventTouchUpInside];
    [self.tableView setTableFooterView:btnTwoYF];
    
}


- (void)presentPage{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *view = [[UIView alloc] init];
    self.clearHudView = view;
    view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
    UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
    r5.numberOfTapsRequired = 1;
    [view addGestureRecognizer:r5];
    
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(30, (screenHeight - (screenWidth - 60) * 900.0 / 500.0) / 2, screenWidth - 60, (screenWidth - 60) * 900.0 / 500.0);
    imageView.image = [UIImage imageNamed:@"661511947049_.pic_hd.jpg"];
    [view addSubview:imageView];
    view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
    [window addSubview:view];
}



- (void)textFieldDidEndEditing:(UITextField *)textField{
    self.buyMoney = textField.text.doubleValue;
    [_tableView reloadData];
}

-(UITableView*)tableView
{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 268, screenWidth, screenHeight-268-49-KNavHeight)];
        _tableView.delegate=self;
        _tableView.rowHeight=80;
        _tableView.dataSource=self;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = _dataDict[@"portfolioFund"];
    return array.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   
      makeUpTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"makeUpTableViewCell" forIndexPath:indexPath];
    NSArray *array = _dataDict[@"portfolioFund"];
    NSDictionary *dict = array[indexPath.row];
    cell.buyMoneyTwo = _buyMoney;
    cell.dataDict = dict;
    
        return cell;
    
}

- (void)setDataDict:(NSDictionary *)dataDict{
    _dataDict = dataDict;
    
}

- (void)buyFund{
    [SVProgressHUD show];
    NSMutableDictionary *fundInfo = [NSMutableDictionary dictionary];
    fundInfo[@"accountNumber"] = kAcount;
    fundInfo[@"portfolioCode"] = _dataDict[@"portfolioCode"];
    
    fundInfo[@"investmentAmount"] = self.moneyTf.text;
    
    fundInfo[@"agreementConfirmed"] = @"0";
    
    if (self.isBankCard==YES) {
        fundInfo[@"payMethod"] = @"0";
    }
    else
    {
        fundInfo[@"payMethod"] = @"1";
    }
    fundInfo[@"buyMode"] = @"0";
    
    fundInfo[@"investorPayId"] = self.investorPayId;
    
    fundInfo[@"currency"] = @"156";
    fundInfo[@"password"] = self.tradePassword;
    fundInfo[@"riskConfrimed"] = @"1";
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    dict[@"methodPath"] = @"/public/product/portfolio/purchase-portfolio-transaction";
    dict[KparametOne] = [self dictionaryToJson:fundInfo];
   
    [HttpRequest sendPostRequestWithURL:nil WithParamets:dict WithJsonString:nil success:^(id result) {
        if ([result[@"code"] isEqualToString:@"0000"]) {
            [SVProgressHUD showInfoWithStatus:@"购买成功"];
            [SVProgressHUD dismissWithDelay:1.5];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.5];
        }
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误，购买失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    return jsonTemp;
}

- (void)initData{
    
    NSDictionary *paramet = @{
                              KparametTwo:@"/public/investor/find-bank"
                              };
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSDictionary *dict = result[@"data"];
        self.bankArray = [NSArray arrayWithArray:dict[@"data"]];
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)getBankCardInfo{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KBankCardInfo};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dataDict = result[@"data"];
            NSDictionary *investorBankDetails = dataDict[@"investorBankDetails"];
            NSArray *bankArrayt = investorBankDetails[@"data"];
            NSDictionary *bankDetail = bankArrayt.firstObject;
            self.bankDetail = bankDetail;
            self.investorPayId= self.bankDetail[@"investorPayId"];
            NSString *imageName = [NSString stringWithFormat:@"icon_%@", bankDetail[@"bankCode"]];
            self.bankIcon.image = [UIImage imageNamed:imageName];
            for (int i = 0; i < self.bankArray.count; i++) {
                NSDictionary *dict = self.bankArray[i];
                if ([bankDetail[@"bankCode"] isEqualToString:dict[@"bankCode"]]) {
                    NSString *banName = dict[@"bankName"];
                    NSString *cardNo = bankDetail[@"bankNumber"];
                    NSString *laterFour = [cardNo substringFromIndex:(cardNo.length - 4)];
                    self.bankInfo.text = [NSString stringWithFormat:@"%@ 尾号：%@", banName, laterFour];
                    break;
                }
            }
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"获取银行卡信息失败"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (void)getRateFee{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    
    paramets[@"portfolioCode"] = _dataDict[@"portfolioCode"];
    paramets[@"investmentAmount"] = self.moneyTf.text;
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KGetFee};
    
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dict = result[@"data"];
            if (![dict[@"salesChargesRate"] isKindOfClass:[NSNull class]]) {
                NSNumber *salesChargesRate = dict[@"salesChargesRate"];
                self.consultRate.text = [NSString stringWithFormat:@"%.2f%%", salesChargesRate.doubleValue];
            }
            if (![dict[@"totalSalesCharge"] isKindOfClass:[NSNull class]]) {
                NSNumber *salesCharges = dict[@"totalSalesCharge"];
                self.consultCost.text = [NSString stringWithFormat:@"%.2f元", salesCharges.doubleValue];
            }
            
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        [SVProgressHUD dismissWithDelay:1.0];
    }];
}

- (IBAction)jumpBtn:(UIButton *)sender {
   
    HDCFMyBankCardVc*vc=[[HDCFMyBankCardVc alloc]init];
    vc.isNeedBlock=YES;
    vc.isXianshiWallet=YES;
    vc.isHiddenDeleteBtn = YES;
    vc.block = ^(NSString *name, NSString *bank, NSString *bankId,BOOL isBankCard) {
        self.isBankCard=isBankCard;
        if (isBankCard==YES) {
            self.investorPayId=bankId;
            self.bankInfo.text = [NSString stringWithFormat:@"%@ *** %@", name, bank];
        }
        else
        {
            self.bankInfo.text = [NSString stringWithFormat:@"现金钱包 余额：%@",  name];
        }
        
    };
    [self.navigationController pushViewController:vc animated:YES];
    
    [SVProgressHUD dismissWithDelay:1.0];
}

- (IBAction)buyBtnClick:(UIButton *)sender {
    NSString *money = self.moneyTf.text;
    
    if (money.length < 1) {
        [SVProgressHUD showInfoWithStatus:@"请输入购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    CGFloat buyMoney = money.doubleValue;
    if (buyMoney < self.minMoney) {
        [SVProgressHUD showInfoWithStatus:@"低于最小购买金额"];
        [SVProgressHUD dismissWithDelay:1.0];
        return;
    }
    
    NSNumber *selfRiskRate = kRiskResult;
    if (!selfRiskRate) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先进行风险评测！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            HDCFRiskTestVc *riskVc = [[HDCFRiskTestVc alloc] init];
            [self.navigationController pushViewController:riskVc animated:NO];
            
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
        return;
    }
    NSNumber *funfRiskRate = _dataDict[@"portfolioRisk"];
    //如果自己是保守型，那么除了保守型基金其他都不能购买
    if ([selfRiskRate isEqual:@1]) {
        if (funfRiskRate.integerValue > selfRiskRate.integerValue) {
            [SVProgressHUD showInfoWithStatus:@"您的风险等级为保守型，不能购买超过风险等级的产品"];
            [SVProgressHUD dismissWithDelay:1.5];
        }
        return;
    }
    if ((funfRiskRate.integerValue > selfRiskRate.integerValue)) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"友情提示" message:@"当前基金组合的风险等级大于您评测的风险等级，确定要购买吗？" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIWindow *window = [UIApplication sharedApplication].keyWindow;
            UIView *view = [[UIView alloc] init];
            self.hitView = view;
            UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
            r5.numberOfTapsRequired = 1;
            [view addGestureRecognizer:r5];
            
            view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
            view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
            InputPassWordView *inputView = [InputPassWordView InputPassWordView];
            inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
            inputView.layer.cornerRadius = 5.0;
            inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
            inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
            inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
            inputView.layer.shadowRadius = 3;//阴影半径，默认3
            inputView.clipsToBounds = YES;
            inputView.delegate = self;
            
            [view addSubview:inputView];
            [window addSubview:view];
        }];
        UIAlertAction * action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        [alert addAction: action1];
        [alert addAction: action2];
        [self presentViewController:alert animated:NO completion:nil];
    }else{
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIView *view = [[UIView alloc] init];
        self.hitView = view;
        UITapGestureRecognizer *r5 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewHit)];
        r5.numberOfTapsRequired = 1;
        [view addGestureRecognizer:r5];
        
        view.frame = CGRectMake(0, 0, screenWidth, screenHeight);
        view.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1];
        InputPassWordView *inputView = [InputPassWordView InputPassWordView];
        inputView.frame = CGRectMake(30, (screenHeight - 182) / 2, screenWidth - 60, 182);
        inputView.layer.cornerRadius = 5.0;
        inputView.layer.shadowColor = ZKcolor(100, 100, 100).CGColor;//shadowColor阴影颜色
        inputView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
        inputView.layer.shadowOpacity = 0.7;//阴影透明度，默认0
        inputView.layer.shadowRadius = 3;//阴影半径，默认3
        inputView.clipsToBounds = YES;
        inputView.delegate = self;
        
        [view addSubview:inputView];
        [window addSubview:view];
    }
    
    
    
    
}

- (void)cancelClick{
    [self.hitView removeFromSuperview];
}

- (void)confirmClickWithPassWord:(NSString *)password{
    self.tradePassword = password;
    [self.hitView removeFromSuperview];
    [self buyFund];
}

- (void)viewHit{
    [self.hitView removeFromSuperview];
}

-(void)keyboardWillBeHidden:(NSNotification*)aNotification{
    if (!(self.moneyTf.text.length < 1)) {
        [self getRateFee];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end
